package com.liy.supercloud.ssoclient.base;

import com.liy.supercloud.ssoclient.interceptor.MvcFeignInterceptorService;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import feign.Feign;
import feign.Contract.Default;
import feign.Feign.Builder;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.FeignContext;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignSupport {

    @Value("${dascloud.authrization.enabled: true}")
    private Boolean enabled;

    @Value("${dascloud.authrization.token-header:JwtToken}")
    private String tokenHeader;

    @Value("${dascloud.authrization.auth-key:AuthKey}")
    private String authKeyHeader;

    @Autowired
    private FeignContext feignContext;

    @Autowired
    private EurekaClient eurekaClient;


    protected MvcFeignInterceptorService getMvcFeignInterceptorService() {
        return new MvcFeignInterceptorService(this.enabled, this.tokenHeader, this.authKeyHeader);
    }

    protected String getServiceHomePageUrl(String serviceName) throws Exception {
        InstanceInfo instanceInfo = this.eurekaClient.getNextServerFromEureka(serviceName, false);
        if (instanceInfo != null) {
            return instanceInfo.getHomePageUrl();
        } else {
            throw new Exception("未查询到该服务:" + serviceName);
        }
    }

    protected Builder getGsonBuilder() {
        return Feign.builder().encoder(new GsonEncoder()).decoder(new GsonDecoder());
    }

    protected <T> T registerMvcFeignBean(String serviceName, Class<T> t1) throws Exception {
        Builder builder = this.getGsonBuilder().contract(new Default());
        if (this.enabled) {
            builder.requestInterceptor(this.getMvcFeignInterceptorService());
        }

        return builder.target(t1, this.getServiceHomePageUrl(serviceName));
    }

    protected <T> T registerJaxrsFeignBean(String serviceName, Class<T> t1) throws Exception {
        Builder builder = this.getGsonBuilder().contract(new JAXRSContract());
        if (this.enabled) {
            builder.requestInterceptor(this.getMvcFeignInterceptorService());
        }

        return builder.target(t1, this.getServiceHomePageUrl(serviceName));
    }
}
